package com.axend.vetwavve.fragment

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.axend.lib_base.base.fragment.BaseVVDFragment
import com.axend.lib_base.databinding.BasePopuViewBottomBinding
import com.axend.lib_base.databinding.BasePopuViewTopBinding
import com.axend.lib_base.engine.toast.toast
import com.axend.lib_base.ext.addFragment
import com.axend.lib_base.utils.ScreenAutoAdapter
import com.axend.lib_base.view.dialog.CustomTipsDialog
import com.axend.lib_base.view.page.PaginationIndicator
import com.axend.lib_base.view.popup.CommonPopupWindow
import com.axend.lib_service.Constant.designSize
import com.axend.vetwavve.BR
import com.axend.vetwavve.R
import com.axend.vetwavve.activity.MainActivity
import com.axend.vetwavve.adapter.PetRecordAdapter
import com.axend.vetwavve.databinding.FragmentPetRecordBinding
import com.axend.vetwavve.viewmodel.PetRecordViewModel
import kotlinx.coroutines.delay

/**
 * @description宠物记录
 * @author admins
 * @time 2024/6/7 15:52
 */
class PetRecordFragment : BaseVVDFragment<PetRecordViewModel, FragmentPetRecordBinding>() {

    private lateinit var petRecordAdapter: PetRecordAdapter
    private var bottomPopup: CommonPopupWindow<BasePopuViewBottomBinding>? = null
    private var topPopup: CommonPopupWindow<BasePopuViewTopBinding>? = null
    private var isSelectAll: Boolean = false
    private val pageSize: Int = 4
    private val offset: Int = 0


    override fun init(savedInstanceState: Bundle?) {
        petRecordAdapter = PetRecordAdapter()

        mBinding.rvPetData.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = petRecordAdapter
            setHasFixedSize(true)
        }

        /*分页组件*/
        mBinding.pageIndicator.setListener(object : PaginationIndicator.OnChangedListener {
            override fun onPageSelectedChanged(
                currentPapePos: Int,
                lastPagePos: Int,
                totalPageCount: Int,
                total: Int
            ) {
                mViewModel.setPageNum(currentPapePos)
            }

            override fun onPerPageCountChanged(perPageCount: Int) {
            }

        })
        initClickListener()
        initObserver()
        mViewModel.getPetInfoCount(searchBinding.etSearch.text.trim().toString())

    }

    private fun initObserver() {
        mViewModel.petInfoList.observe(this) {
            petRecordAdapter.setList(it)
            mBinding.llEmpty.visibility = if (it.isEmpty()) View.VISIBLE else View.GONE
            petRecordAdapter.showCountFooterView(isShow = mViewModel.searchMode.value == true)
        }
        mViewModel.totalCount.observe(this) {
            mBinding.pageIndicator.visibility = if (it == 0) View.GONE else View.VISIBLE
            mBinding.pageIndicator.setTotalCount(it)
        }
        /*分页查询观察*/
        mViewModel.pageNum.observe(this) {
            if (mViewModel.searchMode.value == true) {
                mViewModel.searchAllPetInfoList(searchBinding.etSearch.text.trim().toString())
            } else {
                mViewModel.searchPetInfoList(
                    pageSize = pageSize,
                    offset = (it - 1) * pageSize
                )
            }
        }

        mViewModel.searchMode.observe(this) {
            mBinding.pageIndicator.visibility = if (it) View.GONE else View.VISIBLE
            mBinding.ivEmptyImg.setImageResource(if (it) com.axend.lib_base.R.mipmap.img_wusousuo else com.axend.lib_base.R.mipmap.img_no_message2)
        }
    }

    private fun initClickListener() {
        /*搜索*/
        mBinding.btSearch.setOnClickListener {
            if (searchBinding.etSearch.text.trim().isNullOrEmpty()) {
                toast(getString(com.axend.lib_base.R.string.app_info_input_tips))
                return@setOnClickListener
            }
            /*搜索所有数据*/
            mViewModel.searchAllPetInfoList(searchBinding.etSearch.text.trim().toString())
            mViewModel.getPetInfoCount(searchBinding.etSearch.text.trim().toString())
            mViewModel.setSearchMode(true)

        }

        searchBinding.etSearch.addTextChangedListener {
            if (it.isNullOrEmpty()) {
                mViewModel.setPageNum(offset)
                mViewModel.getPetInfoCount(searchBinding.etSearch.text.trim().toString())
                mViewModel.setSearchMode(false)
            }
        }

        petRecordAdapter.setOnItemClickListener { adapter, view, position ->
            if (petRecordAdapter.data[position].showSelect) {
                return@setOnItemClickListener
            }
            /*跳转详情*/
            addFragment(
                requireActivity(),
                (requireActivity() as MainActivity).getFragmentContainerId(),
                AddOrEditRecordFragment.newInstance(
                    AddOrEditRecordFragment.PARAMS_EDIT,
                    petRecordAdapter.data[position],
                   this
                ),
                this@PetRecordFragment,
                null,
                true
            )
        }

        /*点击编辑按钮*/
        mBinding.ivEdit.setOnClickListener {
            showEditPopup()
            petRecordAdapter.refreshShowChecked(true)
        }

        /*复选点击事件*/
        petRecordAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_select -> {
                    petRecordAdapter.refreshItemSelect(
                        position,
                        !petRecordAdapter.data[position].isSelect
                    )
                    bottomPopup?.binding?.tvAll?.setText(
                        if (!petRecordAdapter.isSelectedAll()) com.axend.lib_base.R.string.app_select_all
                        else com.axend.lib_base.R.string.app_unselect_all
                    )
                    isSelectAll = petRecordAdapter.isSelectedAll()
                }
            }
        }

        /*返回*/
        mBinding.ivBack.setOnClickListener {
            if (requireActivity() is MainActivity) {
                (requireActivity() as MainActivity).onBack()
            }
        }
    }

    /**
     * 批量编辑删除弹窗
     */
    private fun showEditPopup() {
        /*底部弹窗*/
        bottomPopup = object : CommonPopupWindow<BasePopuViewBottomBinding>(
            requireActivity(),
            com.axend.lib_base.R.layout.base_popu_view_bottom
        ) {
            override fun initEvent(binding: BasePopuViewBottomBinding?) {
                /*批量删除*/
                binding?.ivDelete?.setOnClickListener {
                    if (petRecordAdapter.getCheckedMap().isEmpty()) {
                        return@setOnClickListener toast(getString(com.axend.lib_base.R.string.app_tips_please_select))
                    }

                    CustomTipsDialog(
                        context = requireContext(),
                        title = getString(com.axend.lib_base.R.string.app_tips_title),
                        content = getString(com.axend.lib_base.R.string.app_tips_delete),
                        cancelListener = {
                            it.dismiss()
                        }
                    ) { dialog, _ ->
                        /*删除*/
                        for (petMap in petRecordAdapter.getCheckedMap().entries.toList()
                            .reversed()) { // 反向遍历以避免索引问题
                            val key = petMap.key
                            if (key < petRecordAdapter.data.size) { // 先检查索引是否有效
                                petRecordAdapter.data.removeAt(key)
                                petRecordAdapter.notifyItemRemoved(key)
                                petRecordAdapter.notifyItemRangeChanged(
                                    key,
                                    petRecordAdapter.data.size - key - 1
                                )
                                mViewModel.deletePetInfoItem(petMap.value)
                            }
                        }
                        petRecordAdapter.showCountFooterView(isShow = mViewModel.searchMode.value == true && !petRecordAdapter.data.isEmpty())
                        mBinding.llEmpty.visibility =
                            if (petRecordAdapter.data.size == 0) View.VISIBLE else View.GONE
                        /*如果非搜索模式整页数据删除后刷新数据*/
                        if (petRecordAdapter.data.size == 0 && !mViewModel.searchMode.value!!) {
                            mViewModel.getPetInfoCount(
                                searchBinding.etSearch.text.trim().toString(),
                                delay = 500L
                            )
                            mViewModel.searchPetInfoList(
                                pageSize = pageSize,
                                offset = (mViewModel.pageNum.value!! - 1) * pageSize,
                                delay = 500L
                            )
                            (bottomPopup as CommonPopupWindow<BasePopuViewBottomBinding>).dismiss()
                            topPopup?.dismiss()
                        }
                        toast(getString(com.axend.lib_base.R.string.app_tips_delete_success))
                        dialog?.dismiss()
                    }.show()

                }
                binding?.tvAll?.setOnClickListener {
                    isSelectAll = !isSelectAll
                    binding.tvAll.setText(
                        if (!isSelectAll) com.axend.lib_base.R.string.app_select_all
                        else com.axend.lib_base.R.string.app_unselect_all
                    )
                    petRecordAdapter.selectAll(isSelectAll)
                }
            }

        }
        (bottomPopup as CommonPopupWindow<BasePopuViewBottomBinding>).showAtLocation(
            mBinding.clRoot,
            Gravity.BOTTOM,
            0,
            0
        )

        /*顶部弹窗*/
        topPopup = object : CommonPopupWindow<BasePopuViewTopBinding>(
            requireActivity(),
            com.axend.lib_base.R.layout.base_popu_view_top
        ) {
            override fun initEvent(binding: BasePopuViewTopBinding?) {
                /*退出管理*/
                binding?.tvExit?.setOnClickListener {
                    (bottomPopup as CommonPopupWindow<BasePopuViewBottomBinding>).dismiss()
                    topPopup?.dismiss()
                    petRecordAdapter.refreshShowChecked(false)
                    isSelectAll = false
                    petRecordAdapter.selectAll(false)
                }
            }
        }
        (topPopup as CommonPopupWindow<BasePopuViewTopBinding>).popupWindow.isClippingEnabled =
            false

        (topPopup as CommonPopupWindow<BasePopuViewTopBinding>).showAtLocation(
            mBinding.clRoot,
            Gravity.TOP,
            0,
            0
        )
    }


    override fun getBindingVariable(): Int = BR.viewmodel


    override fun onResume() {
        super.onResume()
        ScreenAutoAdapter.match(requireActivity(), designSize)
    }


}